import Axios from 'axios'; // 引入axios
import qs from 'qs'; // 引入qs
import Global from './global'; // 引入global.js
import Vue from 'vue'
import { Message } from 'element-ui';
// axios 默认配置  更多配置查看Axios中文文档
Axios.defaults.timeout = 100000; // 超时默认值

//登录标识位置
var loginInx = location.href.indexOf('/login?');
//截取参数 , 截取问号后面的字符串
var queryString = location.href.substring(location.href.indexOf(location.origin) + location.origin.length + 1).split('?');
var queryArr = is_empty(queryString[1]) ? '' : queryString[1].split('&');
var queryObj = {};
//参数组合对象
for (var i = queryArr.length - 1; i >= 0; i--) {
  var temp = queryArr[i].split('=');
  queryObj[temp[0]] = temp[1];
}
if (loginInx > -1) {
  //登录token是否空
  if (is_empty(queryObj.token)) {
    queryObj.token = '--';
  }
  sessionStorage.setItem('token', queryObj.token);
  delete queryObj.token;
}
//CheckSchoolAppCode做session处理
if (!is_empty(queryObj.CheckSchoolAppCode)) {
  sessionStorage.setItem('CheckSchoolAppCode', queryObj.CheckSchoolAppCode);
  delete queryObj.CheckSchoolAppCode;
}
//请求服务器host字段为空,则使用当前地址的host
if (!is_empty(queryObj.host)) {
  console.log(queryObj.host)
  sessionStorage.setItem('host', queryObj.host);
  redirectUrl += '&host=' + queryObj.host;
  delete queryObj.host;
} else if (is_empty(sessionStorage.getItem('host'))) {
  sessionStorage.setItem('host', location.host);
  redirectUrl += '&host=' + location.host;
}

//请求服务器procotol字段为空,则使用当前地址的procotol
if (!is_empty(queryObj.protocol)) {
  sessionStorage.setItem('protocol', queryObj.protocol);
  redirectUrl += '&protocol=' + queryObj.protocol;
  delete queryObj.protocol;
} else if (is_empty(sessionStorage.getItem('protocol'))) {
  sessionStorage.setItem('protocol', location.protocol.replace(':', ''));
  redirectUrl += '&procotol=' + location.protocol.replace(':', '');
}

console.info(queryObj.protocol)
var paramString = '';
//跳转的路由
if (!is_empty(queryObj.routerUrl)) {
  paramString = queryObj.routerUrl;
  delete queryObj.routerUrl;
}
//剩下的参数作为跳转的参数
paramString += Object.keys(queryObj).length === 0 ? '' : '?';
let inx = 0;
Object.keys(queryObj).forEach(function (key) {
  paramString += (inx === 0 ? '' : '&') + key + '=' + queryObj[key];
  inx++;
})
sessionStorage.setItem('paramString', paramString);
//设置跳转其他内部平台的地址 例如 后台,个人中心
var redirectUrl = '/login?token=' + queryObj.token;
sessionStorage.setItem('redirect_params', '/login?token=' + sessionStorage.getItem('token'));
//设置请求地址
sessionStorage.setItem('host_addr', sessionStorage.getItem('protocol') + '://' + sessionStorage.getItem('host'));
//ItcJwtToken做session处理
if (!is_empty(queryObj.ItcJwtToken)) {
  sessionStorage.setItem('ItcJwtToken', queryObj.ItcJwtToken);
  delete queryObj.ItcJwtToken;
}

Axios.defaults.baseURL = sessionStorage.getItem('host_addr')
// axios.defaults.responseType  = 'json'         // 默认数据响应类型
Axios.defaults.headers.common['Content-Type'] = 'application/json;charset=UTF-8';
// Axios.defaults.withCredentials = true; // 表示跨域请求时是否需要使用凭证
Axios.defaults.withCredentials = false;
// http request 拦截器
// 在ajax发送之前拦截 比如对所有请求统一添加header token
var company = 'BL';
var device_name = 'TE-0600R';

// token 过期，取消多条数据请求，放在多个错误弹窗
const CancelToken = Axios.CancelToken;
// const cancelSource = CancelToken.source();

Axios.interceptors.request.use(
  config => {
    // config.cancelToken = cancelSource.token; // 全局添加cancelToken

    config.cancelToken = new CancelToken(function executor(c) {
      Global.isCancelSource = c;
    })

    if (Global.access_token) {
      config.headers.Authorization = `Bearer ${Global.access_token}`;
      config.headers.CheckSchoolAppCode = sessionStorage.getItem('CheckSchoolAppCode');
      if (!config.headers.hasOwnProperty('DecisionPlatform')) {
        config.headers.DecisionPlatform = `${Global.decisionPlatform}`;
      }
      config.headers.ItcJwtToken = sessionStorage.getItem('ItcJwtToken');
      config.headers.token = sessionStorage.getItem('token');
    }
    var actioncodeArr = config.url.split('/');
    if (config.method == 'post' || config.method == 'put') {
      if (!config.data.hasOwnProperty('company')) {
        if (config.headers['content-type'] != 'multipart/form-data') {
          var requestData = config.data;
          delete config.data;
          config.data = {};
          config.data.company = company;
          config.data.device_name = device_name;
          config.data.sign = `${Global.access_token}`;
          config.data.actioncode = config.method + '_' + actioncodeArr[actioncodeArr.length - 1];
          config.data.data = requestData;
          config.data = qs.stringify(config.data);
        }
      }
    } else if (config.method == 'get' || config.method == 'delete') {
      // 有些请求没有参数则不传 params，为避免下面添加规范报错，在此同一添加 params
      if (config.params === undefined) {
        config.params = {};
      }

      if (!config.params.hasOwnProperty('company')) {
        var requestData = config.params;
        delete config.params;
        config.params = {};
        config.params.company = company;
        config.params.device_name = device_name;
        config.params.sign = `${Global.access_token}`;
        config.params.actioncode = config.method + '_' + actioncodeArr[actioncodeArr.length - 1];
        config.params.data = requestData;
      }
    }

    return config;
  },
  err => {
    return Promise.reject(err);
  }
);

// console.log(location.protocol + '//' + location.host.split(':')[0], 888888)

// http response 拦截器
// ajax请求回调之前拦截 对请求返回的信息做统一处理 比如error为401无权限则跳转到登陆界面
Axios.interceptors.response.use(function (response) {
  // 对响应数据做点什么
  if (!response.config.hasOwnProperty('func')) {
    response.config.func = {};
  }

  if (response.data.hasOwnProperty('data')) {
    var responseData = handleResponseData(response.data, 'need');
  } else {
    var responseData = response.data;
  }

  // 对响应数据做点什么
  Vue.prototype.Ajax_callback(responseData, response.config.func)
  return response;
}, function (error) {
  // console.info(error , 1111)
  // if( !error.response.hasOwnProperty('status') || error.message.indexOf('timeout') === -1 ){
  //     return false;
  // }
  //超时响应
  if (error && error.message && error.message.indexOf('timeout') > -1) {
    Vue.prototype.Ajax_callback({ status: 'timeout', msg: '请求超时' }, error.config.func);
    return false;
  }
  // 对响应错误做点什么
  else if (error.response.status == 401) {
    var config = error.config;
    get_access_token(function () {
      //重新发送请求，并执行回调
      if (config.method == 'post' || config.method == 'put') {
        //qs.stringify反向转换成对象
        config.data = qs.parse(config.data);
      }
      if (!config.hasOwnProperty('func')) {
        config.func = {};
      }
      //执行之前的ajax请求
      Axios(config).then(response => Vue.prototype.Ajax_callback(response.data, config.func));
    });
  } else if (error.response.status == 505) {
    // cancelSource.cancel(); // 取消其他正在进行的请求

    //2后跳回首页
    Message.error("已过期，请登录")
    setTimeout(() => {
      window.location.href = location.protocol + '//' + location.host.split(':')[0]
    }, 1000)
  } else if (error.response.status == 707) {
    Message.error("权限发生改变，请重新登录");

    setTimeout(() => {
      sessionStorage.clear();
      window.location.href = location.protocol + '//' + location.host.split(':')[0]
    }, 1500)
  } else {
    // 对响应数据做点什么
    if (!error.response.config.hasOwnProperty('func')) {
      error.response.config.func = {};
    }
    Vue.prototype.Ajax_callback(error.response.data, error.response.config.func)
  }
  return Promise.reject(error);
});

export default Axios; // 这句千万不能漏下！！！

/**
 * 获取access_token 方法封装
 */
function get_access_token(callback) {
  Axios.get('/accessToken', {
    params: { client_id: Global.client_id, secret: Global.secret }
  }).then(response => {
    let data = response.data.data
    Global.access_token = data.access_token;
    localStorage.setItem('token', Global.access_token);
    callback();
  });
}
